package com.liaoyifan.core.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import org.springframework.web.filter.OncePerRequestFilter;

@SuppressWarnings("unused")
public class SecurityHeadersFilter extends OncePerRequestFilter {
    @SuppressWarnings("NullableProblems")
    @Override
    protected void doFilterInternal(
            HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        // 基础安全头
        response.setHeader("X-Content-Type-Options", "nosniff");
        response.setHeader("Cross-Origin-Resource-Policy", "same-site");
        response.setHeader("Referrer-Policy", "strict-origin-when-cross-origin");
        response.setHeader("Permissions-Policy", "geolocation=(), microphone=(), camera=()");
        // 现代浏览器不需XSS保护头
        response.setHeader("X-XSS-Protection", "0");
        // 强制全站HTTPS（包括HTTP请求）
        response.setHeader(
                "Strict-Transport-Security", "max-age=31536000; includeSubDomains; preload");
        // 动态CSP
        String csp =
                "default-src 'self'; "
                        + "script-src 'self' 'unsafe-inline'; "
                        + "style-src 'self' 'unsafe-inline'; "
                        + "img-src 'self' data:; "
                        + "font-src 'self'; "
                        + "connect-src 'self'; "
                        + "frame-ancestors 'none';"; // 关键防护
        response.setHeader("Content-Security-Policy", csp);
        filterChain.doFilter(request, response);
    }
}
